package log;
import java.io.*;
import java.util.*;


public class Logger {
	String filename;
	private int maxSize;
	static int id = 0;
	LinkedList<LogRecord> ts;

	public Logger(String filename) {
		this(filename, 100);
	}
	
	public Logger(String filename, int maxSize) {
		ts = new LinkedList<LogRecord>();
		File f = new File(filename);
		if (f.exists()) {
			try {
				BufferedReader br = new BufferedReader(new FileReader(f));
				String line, logStr = null;
				String lineSeparator = System.getProperty("line.separator");

				while ((line = br.readLine()) != null) {
					if (isLogHead(line)) {
						if (logStr != null) {
							LogRecord lr = new LogRecord(logStr);
							ts.addLast(lr);
						}
						logStr = line;
					}
					else
						logStr += lineSeparator + line;
				}
				if (logStr != null) {
					LogRecord lr = new LogRecord(logStr);
					ts.addLast(lr);
				}

				br.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		this.filename = filename;
		this.setMaxSize(maxSize);
	}
	
	public void writeLog(String message) {
		LogRecord lr = new LogRecord(message);
		ts.addLast(lr);
		if (ts.size() > maxSize)
			ts.removeFirst();
		Iterator<LogRecord> iter = ts.iterator();
		PrintWriter pw;
		try {
			pw = new PrintWriter(new BufferedWriter(new FileWriter(filename)));

			int count = 0;
			while (iter.hasNext() && count++<maxSize) {
				pw.println(iter.next().toString());
			}

			pw.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void close() {
	}
	
	public boolean isLogHead(String str) {
		try {
			LogRecord.analyzeHead(str);
		} catch(Exception e) {
			return false;
		}
		return true;
	}

	public void setMaxSize(int maxSize) {
		this.maxSize = maxSize;
	}
}
